import crypto from 'crypto-js'
import { Base64 } from 'js-base64'
import Taro from '@tarojs/taro'
import { getUploadSignature } from "_api/base-api"
/* 上传最大限制 */
const MAX_UPLOAD_SIZE = 10 /* M */
// 计算签名。
function computeSignature (accessKeySecret, canonicalString) {
  return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret))
}

const date = new Date()
date.setHours(date.getHours() + 1)
const policyText = {
  expiration: date.toISOString(), // 设置policy过期时间。
  conditions: [
    // 限制上传大小。
    ["content-length-range", 0, MAX_UPLOAD_SIZE * 1024 * 1024],
  ],
}
/* 设置签名过期时间 -- 半小时 */
function setPastTime () {
  const time = + new Date() + (0.5 * 60 * 60 * 1000)
  Taro.setStorageSync('uploadSignaturePastTime',time)
}
/**
 * 获取签名函数
 * @returns 签名数据
 */
export const getUploadSignatureFun = async () => {
  try {
    const result = await getUploadSignature()
    return result
  } catch (error) {
    console.log(error,'getUploadSignatureError')
  }
}
/**
 * @description 客户端获取oss上传签名
 * @link 相关文档 https://help.aliyun.com/document_detail/92883.html?spm=a2c4g.11186623.6.1714.34ba3ba42qx5NK#section-mx7-v31-uy7
 * @param {*} filePath 文件路径
 * @param {*} signatureData 签名数据
 * @returns 
 */
export const getFormDataParams = async (filePath, signatureData = undefined) => {
  // let result = {};
  // if (Taro.getStorageSync('uploadSignature')) {
  //   result = JSON.parse(Taro.getStorageSync('uploadSignature'))
  //   /* 刷新签名 1天一次 */
  //   if (Taro.getStorageSync('uploadSignaturePastTime')) {
  //     if (Taro.getStorageSync('uploadSignaturePastTime') <= + new Date()) {
  //       result = await getUploadSignature()
  //       Taro.setStorageSync('uploadSignature', JSON.stringify(result))   
  //       setPastTime()
  //     }
  //   } else {
  //     setPastTime()
  //   }
  // } else {
  //   try {
  //     result = await getUploadSignature()
  //     Taro.setStorageSync('uploadSignature', JSON.stringify(result))   
  //     setPastTime()
  //   } catch (error) {
  //     console.log(error,'getUploadSignatureError')
  //   }
  // }
  let result = signatureData ? signatureData : await getUploadSignatureFun()
  /* 获取上传所需配置参数 */
  const { data: { host, key, Credentials: credentials } } = result
  const policy = Base64.encode(JSON.stringify(policyText)) // policy必须为base64的string。
  const signature = computeSignature(credentials.AccessKeySecret, policy)
  /* 保存临时地址 */
  let filePathTem = filePath
  const reg = /(\.jpg$|\.png$|\.bmp$|\.gif$|\.mp3$|\.aac$|\.wav$|\.pcm$|\.PCM$|\.m4a$|\.ogg$|\.ape$|\.amr$|\.wma$|\.mp4$|\.aiff$|\.caf$)/
  /* 匹配文件后缀 */
  filePathTem = reg.exec(filePathTem) ? reg.exec(filePathTem)[0] : ''
  const formData = {
    host,
    key: key + (+new Date()) + filePathTem,
    OSSAccessKeyId: credentials.AccessKeyId,
    signature,
    policy,
    'x-oss-security-token': credentials.SecurityToken,
    'success_action_status': '200'
  }
  return formData
}
